<?php

namespace mpend\modules\shop\models;

use Yii;
use yii\data\ActiveDataProvider;
use common\models\shop\ShopProduct;
use common\models\shop\ShopGoods;

/**
 * This is the model class for table "{{%dynamic}}".
 *
 * @property int $id
 * @property string $user_id 用户ID
 * @property string $content
 * @property int $direction 动态类型：0主动动态，1被动动态
 * @property int $retweet_id 转发动态原始ID
 * @property int $status
 * @property string $created_at
 * @property string $updated_at
 * @property string $deleted_at
 */
class PackBalanceSearch extends \common\models\shop\ShopCart {

    /**
     * Creates data provider instance with search query applied
     *
     * @return ActiveDataProvider
     */
    public static function findByUserid($userid) {
        $model = static::find()->where(['user_id' => $userid])->with('goods', 'product')->all();
        if (empty($model)) {
            return $model;
        }

        $data = [];
        foreach ($model as $cart) {
            $goods = $cart->goods;
            if (!$goods) {
                continue;
            }
            $data[$cart->goods_id] = [
                'id' => $cart->goods_id,
                'name' => $goods->name,
                'price' => $goods->price,
                'discount' => $goods->discount,
                'number' => $cart->num,
                'type_id' => $cart->product->type_id,
                'brand_id' => $cart->product->brand_id,
                'subtotal' => ($goods->price - $goods->discount) * $cart->num,
            ];
        }

        return $data;
    }

    public function fields() {
        return [
            'id',
            'name' => function() {
                return $this->product ? $this->product->name : '';
            },
            'sku' => function() {
                return $this->goods ? $this->goods->name : '';
            },
            'price' => function() {
                return $this->goods ? floatval($this->goods->price) : 0;
            },
            'num',
            'thumb' => function() {
                if ($this->goods && $this->goods->cover) {
                    return $this->goods->cover;
                }
                if ($this->product && $this->product->cover) {
                    return $this->product->cover;
                }
                return '';
            },
            'checked' => function() {
                return $this->status == static::STATUS_CHECKED;
            },
            'status' => function() {
                if (!($this->goods && $this->product)) {
                    return false;
                }
                return $this->goods->status == ShopGoods::STATUS_ACTIVE && $this->product->status == ShopProduct::STATUS_ACTIVE;
            },
            'product_id',
            'goods_id',
        ];
    }

}
